package com.fsnmt.maizhuanbao.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class PicturePickUtils implements Serializable{
	public static final int REQUEST_CODE_CAMERA = 101;
	public static final int REQUEST_CODE_LOCAL = 102;
	public static final int REQUEST_CODE_CUT_PICTURE = 103;
	public static final String KEY_PICTURE = "pick_picture";
	public static final String KEY_CUT_PICTURE = "cut_picture";
	public  String cameraPath;
	private String cropPath;
	private String dirName ;

	public PicturePickUtils(String dirName){
		this.dirName = dirName;
	}

	public PicturePickUtils(){
		this.dirName = CacheManager.getInstance().getPickFolder();
	}

	/**
     * 照相获取原图图片
     */
	public void selectPicFromLocal(Activity activity,Fragment fragment) {
		Intent intent;
		if (Build.VERSION.SDK_INT < 19) {
		    intent = new Intent(Intent.ACTION_GET_CONTENT);
		    intent.setType("image/*");
		} else {
		    intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		}
		if (null != activity) {
			activity.startActivityForResult(intent, REQUEST_CODE_LOCAL);
		}
		else if(null!=fragment)
			fragment.startActivityForResult(intent, REQUEST_CODE_LOCAL);
	}
	
	 /**
     * 相机拍照获取原图照片
     */
    public boolean selectPicFromCamera(Activity activity,Fragment fragment) {

		if (!isSDCARDMounted()) {
			ToastUtils.show(null == activity ? fragment.getActivity() : activity, "没有内存卡");
			return false;
		}

		Activity a = null == activity ? fragment.getActivity() : activity;
		if (!SystemUtils.checkCameraPermission(a)) {
			SystemUtils.getCameraPermission(a, REQUEST_CODE_CAMERA);
			return false;
		}

		cameraPath = createFilePath(false);
		if (null != activity){
			activity.startActivityForResult(
					new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(cameraPath)),
					REQUEST_CODE_CAMERA);
		}else if(null!=fragment) {
			Uri tempUri = getTempUri(cameraPath);
			fragment.startActivityForResult(
					new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, tempUri),
					REQUEST_CODE_CAMERA);
		}
        return true;
    }


	/**
     * 获取系统相册后调用这个方法去裁剪图片
     */
	public void cropImageUriWithURi(Activity activity,Fragment fragment,Uri uri,int aspectX,int aspectY,int outputX,int outputY) {
		if (uri == null) {
			return;  
		}
		if (!isSDCARDMounted()) {
            ToastUtils.show(null==activity?fragment.getActivity():activity, "没有内存卡");
            return ;
        }
		Intent intent = new Intent("com.android.camera.action.CROP");
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			String url=getPath(null==activity?fragment.getActivity():activity,uri);
			intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");  
		}else{
			intent.setDataAndType(uri, "image/*");  
		}  
		// 设置裁剪  
		intent.putExtra("crop", "true");
		if(0 != aspectX)
			intent.putExtra("aspectX", aspectX);
		if(0 != aspectY)
			intent.putExtra("aspectY", aspectY);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("return-data", true);  
		cropPath = createFilePath(true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(cropPath));
		intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG);
		if(null!=activity) {
			activity.startActivityForResult(intent, REQUEST_CODE_CUT_PICTURE);
		}else if(null!=fragment)
			fragment.startActivityForResult(intent, REQUEST_CODE_CUT_PICTURE);
	}
	
	
	public void cropImageUriByCamera(Activity activity,Fragment fragment,int aspectX,int aspectY ,int outputX,int outputY) {

//		Activity a = null == activity ? fragment.getActivity() : activity;
//		if (!SystemUtils.checkCameraPermission(a)) {
//			SystemUtils.getCameraPermission(a, REQUEST_CODE_CUT_PICTURE);
//			return;
//		}

		if(TextUtils.isEmpty(cameraPath)){
			cameraPath = CacheManager.getInstance().getCache().getAsString(KEY_PICTURE);
		}
		 Uri photoUri = getTempUri(cameraPath);
		 Intent intent = new Intent("com.android.camera.action.CROP");
		 intent.setDataAndType(photoUri, "image/*");
		 intent.putExtra("crop", "true");
		if(0 != aspectX)
		 intent.putExtra("aspectX", aspectX);
		if(0 != aspectY)
		 intent.putExtra("aspectY", aspectY);
		 intent.putExtra("outputX", outputX);
		 intent.putExtra("outputY", outputY);
//		 intent.putExtra("scale", true);
		 cropPath = createFilePath(true);
		 intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(cropPath));
		 intent.putExtra("return-data", true);
		 intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG);
		 intent.putExtra("noFaceDetection", true); // no face detection
		if(null!=activity){
			activity.startActivityForResult(intent, REQUEST_CODE_CUT_PICTURE);
		}else if(null!=fragment) {
			fragment.startActivityForResult(intent, REQUEST_CODE_CUT_PICTURE);
		}
	}
	
	/**
	 * 直接照片file调用裁剪
	 */
    public  void cropImageUriWithFile(Activity activity,Fragment fragment,File imageFile,int aspectX,int aspectY ,int outputX,int outputY) {
    	if (!isSDCARDMounted()) {
            ToastUtils.show(null==activity?fragment.getActivity():activity, "没有内存卡");
            return ;
        }
    	if(null==imageFile || !imageFile.exists()){
    		return;
    	}

//		if (!SystemUtils.checkCameraPermission(a)) {
//			SystemUtils.getCameraPermission(a, REQUEST_CODE_CUT_PICTURE);
//			return;
//		}

		 Uri photoUri = Uri.fromFile(imageFile);
		 Intent intent = new Intent("com.android.camera.action.CROP");
		 intent.setDataAndType(photoUri, "image/*");
		 intent.putExtra("crop", "true");
		if(0 != aspectX)
			intent.putExtra("aspectX", aspectX);
		if(0 != aspectY)
		 intent.putExtra("aspectY", aspectY);
		 intent.putExtra("outputX", outputX);
		 intent.putExtra("outputY", outputY);
		 cropPath = createFilePath(true);
		 intent.putExtra(MediaStore.EXTRA_OUTPUT,getTempUri(cropPath));
		 intent.putExtra("return-data", true);
		 intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG);
		 intent.putExtra("noFaceDetection", true); // no face detection
		if(null!=activity)
		 activity.startActivityForResult(intent, REQUEST_CODE_CUT_PICTURE);
		else if(null!=fragment)
			fragment.startActivityForResult(intent, REQUEST_CODE_CUT_PICTURE);
	}
	  
    
    public void clean(){
    	if (isSDCARDMounted()) {
            FileUtils.deleteAllFiles(new File(dirName));
        }
    }
    
    private String createFilePath(boolean isCrop) {
    	String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    	if(isCrop){
    		String imageFileName = "JPEG_" + timeStamp + "_cut.png";
			String path = dirName+File.separator+"cutPicture"+File.separator+imageFileName;
			CacheManager.getInstance().getCache().put(KEY_CUT_PICTURE,path);
    		return path;
    	}else {
    		String imageFileName = "JPEG_" + timeStamp + "_take.png";
			String path =  dirName+File.separator+imageFileName;
			CacheManager.getInstance().getCache().put(KEY_PICTURE, path);
			String asString = CacheManager.getInstance().getCache().getAsString(KEY_PICTURE);
			return path;
		}
	}
    
    
    private File creatFile(boolean isCrop){
    	File temp  = null;
    	String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    	if(isCrop){
    		String imageFileName = "JPEG_" + timeStamp + "_cut.png";
    		temp = new File(dirName+File.separator+"cutPicture"+File.separator+imageFileName);
    	}else {
    		String imageFileName = "JPEG_" + timeStamp + "_take.png";
    		temp = new File(dirName+File.separator+imageFileName);
		}
//      DIRECTORY_PICTURES下载的图片保存的位置  DIRECTORY_DCIM //相机拍摄的图片和视频保存的位置
//      File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        temp.getParentFile().mkdirs();
        if(!temp.exists()){
        	try {
				temp.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return temp;
    }
    
    
    private  Uri getTempUri(String filePath) {
		File tempFile = getTempFile(filePath);
		return Uri.fromFile(tempFile);
	}
    
	private File getTempFile(String filePath) {
		File f = new File(filePath);
		boolean mkdir = f.getParentFile().mkdirs();
		if (!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return f;
	}
    
	public  Bitmap decodeUriAsBitmap(Activity activity,Fragment fragment,Uri uri) {
		Bitmap bitmap = null;
		try {
			if(null!=activity)
				bitmap = BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(uri));
			else {
				bitmap = BitmapFactory.decodeStream(fragment.getActivity().getContentResolver().openInputStream(uri));
			}
		} catch (FileNotFoundException e) {
			return null;
		}
		return bitmap;
	}
    
    /**
     * 判断是否存在外部存储
     * @return
     */
    private boolean isSDCARDMounted() {
		String status = Environment.getExternalStorageState();
		return status.equals(Environment.MEDIA_MOUNTED);
	}
    
    /**在onActivityResult监听到  requestCode 获取当次选择或者拍照的拍照File，也可以获取裁剪之后的图片*/
    public File getPictureFile(Activity activity,Fragment fragment,int requestCode,Intent data){
    	if(REQUEST_CODE_CAMERA == requestCode){
			if(TextUtils.isEmpty(cameraPath)){
				cameraPath = CacheManager.getInstance().getCache().getAsString(KEY_PICTURE);
			}

			if(null==cameraPath)
				throw  new RuntimeException("cameraPath = null,paht="+ CacheManager.getInstance().getUserDir());
    		return getTempFile(cameraPath);
    	}else if(REQUEST_CODE_LOCAL == requestCode){
    		if (data != null) {
                Uri selectedImage = data.getData();
                if (selectedImage != null) {
                	String[] filePathColumn = { MediaStore.Images.Media.DATA };
					Cursor cursor = null;
					if(null!=activity) {
						cursor = activity.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
					}else{
						cursor = fragment.getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
					}
                    if (cursor != null) {
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String picturePath = cursor.getString(columnIndex);
                        cursor.close();
                        cursor = null;
                        if (TextUtils.isEmpty(picturePath)|| picturePath.equals("null")) {
                            return null;
                        }else{
                        	return new File(picturePath);
                        }
                    }
                }
    		}
    	}else if(REQUEST_CODE_CUT_PICTURE == requestCode){
			if(TextUtils.isEmpty(cropPath)){
				cropPath = CacheManager.getInstance().getCache().getAsString(KEY_CUT_PICTURE);
			}
			File tempFile = getTempFile(cropPath);
			if(0==tempFile.length()) {
				Bitmap bmap = data.getParcelableExtra("data");
				if(null!=bmap){
					FileUtils.saveBitMap(bmap,tempFile);
				}
			}
    		return tempFile;
    	}
    	return null;
    }

	/***
	 * 重要方法*以下是4.4图库url变动方法
	 ***************/
	@TargetApi(Build.VERSION_CODES.KITKAT)
	private String getPath(final Context context, final Uri uri) {
		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}
				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {
				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));
				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];
				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}
				final String selection = MediaColumns._ID + "=?";
				final String[] selectionArgs = new String[]{split[1]};
				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();
			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}
		return null;
	}
    
    /**
     * Get the value of the data column for this Uri . This is useful for
     * MediaStore Uris , and other file - based ContentProviders.
	 *
     * @param context
     *            The context.
     * @param uri
     *            The Uri to query.
     * @param selection
     *            (Optional) Filter used in the query.
     * @param selectionArgs
     *            (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    private String getDataColumn(Context context, Uri uri,
            String selection, String[] selectionArgs) {
       Cursor cursor = null;
       final String column = MediaColumns.DATA;
        final String[] projection = { column };
        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
               final int index = cursor.getColumnIndexOrThrow(column);
               return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
               cursor.close();
       }
		return null;
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	private boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
   }

   /**
    * @param uri
    *            The Uri to check.
	* @return Whether the Uri authority is DownloadsProvider.
	*/
   private boolean isDownloadsDocument(Uri uri) {
	   return "com.android.providers.downloads.documents".equals(uri
			   .getAuthority());
   }

   /**
    * @param uri
    *            The Uri to check.
	* @return Whether the Uri authority is MediaProvider.
	*/
   private boolean isMediaDocument(Uri uri) {
	   return "com.android.providers.media.documents".equals(uri
			   .getAuthority());
   }

   /**
    * @param uri
    *            The Uri to check.
    * @return Whether the Uri authority is Google Photos.
    */
   private boolean isGooglePhotosUri(Uri uri) {
       return "com.google.android.apps.photos.content".equals(uri
               .getAuthority());
   }

	public class CropParams {
		int aspectX;
		int aspectY;
		int outputX;
		int outputY;

		public CropParams(int aspectX, int aspectY, int outputX, int outputY) {
			this.aspectX = aspectX;
			this.aspectY = aspectY;
			this.outputX = outputX;
			this.outputY = outputY;
		}
	}
}
